import request from "../../../../../plugins/request"
import {checkPhone} from "../../../../../utils/utils";

Component({
	properties: {
		sjh: {
			type: String,
			value: "",
		},
	},
	data: {
		btnDisable: false, // 按钮是否禁用，当获取过验证码时，按钮暂时被禁用
		btnText: "获取验证码", // 按钮文案
		initCountDown: 120, // 初始化倒计时
		countDown: 120, // 倒计时
	},
	methods: {
		//获取手机短信验证码
		getPhoneVerifyCode() {
			// 检查用户有没有输入手机号码
			if (!this.data.sjh) {
				wx.showToast({
					title: "请输入手机号码",
					icon: "none",
					duration: 2000,
				})
				return
			}
			//校验用户输入的手机号码是否合法
			if (!checkPhone(this.data.sjh)) {
				wx.showToast({
					title: "手机号码的格式不正确，请检查",
					icon: "none",
					duration: 2000,
				})
				return
			}
			request({
				url: "api/wx/send-message-code",
				data: {
					sjh: this.data.sjh,
				},
				errorHandle: true,
				showLoading: true,
			}).then((data) => {
				wx.showToast({
					title: "验证码已发送，请留意手机短信",
					icon: "none",
					duration: 2000,
				})
				this.setData({
					btnDisable: true,
					btnText: `${this.data.countDown}s`,
					countDown: this.data.initCountDown,
				})
				//开启倒计时
				const timer = setInterval(() => {
					this.setData({
						countDown: this.data.countDown - 1,
						btnText: `${this.data.countDown}s`,
					})
					if (this.data.countDown <= 0) {
						clearInterval(timer)
						this.setData({
							btnDisable: false,
							btnText: "获取验证码",
							countDown: this.data.initCountDown,
						})
					}
				},1000)
				console.log(data, "data")
			})
		},
	},
})
